<?php

class SearchController extends ControllerBase
{
	public function initialize()
    {
        $this->tag->setTitle('Tìm kiếm');
        parent::initialize();
    }

    public function indexAction()
    {
        $generate_time = microtime_float();
    	$request = new Phalcon\Http\Request();
    	$keyword = $request->getPost("keyword");
        //Cache data for 120s
        $frontCache = new Phalcon\Cache\Frontend\Data(array(
            "lifetime" => 120
        ));
        $cache = new Phalcon\Cache\Backend\Memcache($frontCache, array(
            "servers" => array(
                    array(
                            "host" => "127.0.0.1",
                            "port" => "11211",
                            "weight" => "1"
                    )
            )
        ));

        // Try to get cached records
        $cacheKey = 'product_search_'.md5($keyword).'.cache';
        $result    = $cache->get($cacheKey);
        $from_data = 'From cache';
        if ($result === null) {
            $product = new Product();
            $result = $product::find(array(
                "conditions" => "sp_name LIKE '%$keyword%'",
                "limit" => 10
            ));
            $cache->save($cacheKey, $result);
            $from_data = 'From database';
        }

        $time_fload = microtime_float() - $generate_time;
    	
    	$this->view->setVar('result',$result);
        $this->view->setVar('keyword',$keyword);
        $this->view->setVar('from_data',$from_data);
        $this->view->setVar('time_fload',$time_fload);
    }

}